/**
 * Copyright 2013 ABSir's Studio
 * 
 * All right reserved
 *
 * Create on 2013-5-2 上午9:39:01
 */
package com.absir.android.view.listener;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.view.View;

import com.absir.core.kernel.KernelClass;
import com.absir.core.kernel.KernelLang.CauseRuntimeException;
import com.absir.core.kernel.KernelReflect;
import com.absir.core.kernel.KernelString;

/**
 * @author absir
 * 
 */
public abstract class Listener {

	/** target */
	Object target;

	/** method */
	String method;

	/** targetMethod */
	private Method targetMethod;

	private boolean noArgs;

	/**
	 * @param view
	 * @param target
	 * @param method
	 */
	public final void listener(View view, Object target, String method) {
		if (!KernelString.isEmpty(method)) {
			this.target = target;
			this.method = method;
			listener(view);
		}
	}

	/**
	 * @param view
	 * @param target
	 * @param method
	 */
	public final void listener(View view, Object target, Method method) {

	}

	/**
	 * @param args
	 * @throws RuntimeException
	 */
	public Object invoke(Object... args) {
		if (method != null) {
			targetMethod = KernelReflect.assignableMethod(target.getClass(), method, 0, true,
					KernelClass.parameterTypes(args));
			if (targetMethod == null) {
				noArgs = true;
				targetMethod = KernelReflect.declaredMethod(target.getClass(), method);
			}

			method = null;
		}

		if (targetMethod != null) {
			try {
				if (noArgs) {
					targetMethod.invoke(target);

				} else {
					targetMethod.invoke(target, args);
				}

			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				throw new CauseRuntimeException(e);
			}
		}

		return null;
	}

	/**
	 * @param view
	 */
	protected abstract void listener(View view);
}
